﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.UI.WebControls;
using GrailTechnology.AutoTags.Providers;

namespace GrailTechnology.AutoTags.DataType.usercontrols
{
    public partial class AutoTagsPostInstall : System.Web.UI.UserControl
    {
        private Dictionary<string, string> _providers;

        Config _c;

        protected override void OnInit(EventArgs e)
        {
            _providers = new Dictionary<string, string>();
            _c = Config.Instance;
            CalaisKey.Text = _c.OpenCalaisApiKey;
            TagGroup.Text = _c.TagGroup;
            IncludeAliases.Text = _c.PropertyAliasesToUse;
            ExcludeAliases.Text = _c.PropertyAliasesToExclude;
            ProviderList.DataSource = LoadTagProviders();
            ProviderList.DataBind();
        }
        
        protected void Button1_Click(object sender, EventArgs e)
        {
            _c.OpenCalaisApiKey = CalaisKey.Text;
            _c.Provider = _providers[ProviderList.SelectedItem.Value];
            _c.TagGroup = TagGroup.Text;
            _c.PropertyAliasesToUse = IncludeAliases.Text;
            _c.PropertyAliasesToExclude = ExcludeAliases.Text;
            _c.Write();
            Literal1.Visible = true;
        }

        protected IEnumerable<ListItem> LoadTagProviders()
        {
            var tagInterface = typeof(ITagProvider);
            var assembly = Assembly.Load("GrailTechnology.AutoTags.Providers");
            var providers = assembly.GetTypes().Where(t => tagInterface.IsAssignableFrom(t) && t != tagInterface);

            var list = new List<ListItem>();

            _providers.Clear();

            foreach (var provider in providers)
            {
                list.Add(new ListItem(provider.Name, string.Concat(provider.FullName, ", ", provider.Assembly.GetName().Name)));
                _providers.Add(provider.Name, string.Concat(provider.FullName, ", ", provider.Assembly.GetName().Name));
            }

            return list;
        }

        protected void ProviderList_SelectedIndexChanged(object sender, EventArgs e)
        {
            pnlOpenCalaisKey.Visible = ProviderList.SelectedItem.Text == typeof(OpenCalaisService).Name;
        }
    }
}